package it.canraid.texthere;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

import android.os.Handler;

public class FntwAgent extends Thread {
	private static boolean someoneIsRunning=false;
	
	public String json="{ }";
	public Handler handlerTo=null;
	
	public FntwAgent(String json, Handler handlerTo){
		super();
		if (json!=null)
			this.json=json;
		
		this.handlerTo=handlerTo;
	}
	
	public void run(){
		String response=sendAndWaitResponse();
		if (response == null || handlerTo == null)
			return;
		
		handlerTo.obtainMessage(Cparams.HANDLER_RESPONSE_JSON, 0, 0, response).sendToTarget();
	}
	
	public String sendAndWaitResponse(){
		if (!someoneIsRunning)
			someoneIsRunning=true;
		else
			return null;
		
		String response="{ }";
		DataOutputStream   wr =null;
		BufferedReader in = null;
		HttpURLConnection connection =null;
		try{
			URL url = new URL(Cparams.URL_PATH);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);//abilita la scrittura
			connection.setRequestMethod("POST");	//settaggio del metodo	
			connection.setConnectTimeout(Cparams.TIMEOUT_CONNECTION_MS);
			wr = new DataOutputStream (connection.getOutputStream());
			wr.writeBytes(json);
			wr.flush();
			wr.close();
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String inputLine;
			StringBuffer json = new StringBuffer();
			while ((inputLine = in.readLine()) != null) {
				json.append(inputLine);
			}
			response=json.toString();
		}
		catch(Exception e){
			String error=e.getMessage();
			error=error.replaceAll("\"", " \\\"");
			error=error.replaceAll("\'", " \\\'");
			if (e instanceof SocketTimeoutException ){
				//TODO timeout connection
				response="{ \""+Cfunctions.type_operation+"\": \"unknown\", " + "\""+Cfunctions.error+"\": \""+Cparams.NTW_CONN_TIMEOUT_001+"\" }";
			}else{
				response="{ \""+Cfunctions.type_operation+"\": \"unknown\", " + "\""+Cfunctions.error+"\": \""+Cparams.INTERNAL_NTW_002+error+"\" }";
			}
		}
		finally{
			someoneIsRunning=false;
			try {
				if (wr != null)
					wr.close();
			} 
			catch (IOException e) {
				e.printStackTrace();
			}
			
			try {
				if (connection!=null)
					connection.disconnect();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			try{
				if (in!=null)
					in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		return response;
	}
}
